package user

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"time"
)

type userRoleRepository struct {
	tenant_db.TenantDB
}

// NewUserRoleRepository 构造函数
func NewUserRoleRepository() UserRoleRepositoryIface {
	return &userRoleRepository{}
}

// GetUsersByRoleId 根据角色编号获取用户列表
func (r *userRoleRepository) GetUsersByRoleId(ctx context.Context, roleId int64) ([]*GfyUserRoleRelationPo, error) {
	list := make([]*GfyUserRoleRelationPo, 0)
	err := r.GetTenantDB(ctx).Where("role_id = ?", roleId).Find(&list).Error
	return list, err
}

// AddRoleForUser 为账号增加角色
func (r *userRoleRepository) AddRoleForUser(ctx context.Context, userId int64, roleIds []int64) error {
	db := r.GetTenantDB(ctx)
	db.Begin()

	db.Table(GfyUserRoleRelationPo{}.TableName()).
		Where("user_id = ? and role_id in (?)", userId, roleIds).
		Updates(map[string]interface{}{
			"is_deleted":  constants.IsDeletedTrue,
			"modified_on": time.Now(),
		})

	for _, roleId := range roleIds {
		uRole := &GfyUserRoleRelationPo{
			UserId:    userId,
			RoleId:    roleId,
			CreatedOn: time.Now(),
			//CreatedBy:  "",
			ModifiedOn: time.Now(),
			//ModifiedBy: "",
		}
		err := db.Save(uRole).Error
		if err != nil {
			db.Callback()
			return err
		}
	}

	db.Commit()

	return nil
}

// GetRolesByUserIds 根据角色编号获取用户列表
func (r *userRoleRepository) GetRolesByUserIds(ctx context.Context, userIds []int64) ([]*GfyUserRoleRelationPo, error) {
	var list = make([]*GfyUserRoleRelationPo, 0)
	err := r.GetTenantDB(ctx).Where("user_id in (?) and is_deleted = ?", userIds, constants.IsDeletedFalse).Find(&list).Error
	return list, err
}
